import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../service/post_service.dart';
import '../models/post_model.dart';
import '../models/comment_model.dart';
import '../widgets/error_widget.dart';
import 'comments_screen.dart';

class PostsScreen extends StatefulWidget {
  final int? userId; // 新增：支持按用户ID筛选
  final String? userName; // 新增：用户名称
  final int? postId; // 新增：帖子id

  const PostsScreen({super.key,   this.userId,
    this.userName,this.postId});

  @override
  _PostsScreenState createState() => _PostsScreenState();
}

class _PostsScreenState extends State<PostsScreen>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  late Future<List<Post>> _futurePosts;
  late Future<Post> _futurePostById;

  late Future<List<Comment>> _futureComments;
  int? _filterUserId; // 当前筛选的用户ID
  int? _postId; // 当前筛选的帖子ID

  @override
  void initState() {
    super.initState();
    _filterUserId = widget.userId;
    final postService = context.read<PostService>();

    if (_postId != null) {
      // 加载指定用户的帖子
      _futurePostById = postService.getPost(_postId!);
      _futurePosts.add(_futurePostById);
    }else  if (_filterUserId != null) {
      // 加载指定用户的帖子
      _futurePosts = postService.getPostsByUser(_filterUserId!);
    } else {
      // 加载所有帖子
      _futurePosts = postService.getPosts();
    }

    _futureComments = postService.getAllComments();
    _tabController = TabController(length: 2, vsync: this);

  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('帖子与评论'),
        bottom: TabBar(
          controller: _tabController,
          tabs: const [
            Tab(text: '帖子'),
            Tab(
              text: '评论',
            )
          ],
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        children: [
          // 帖子列表
          FutureBuilder<List<Post>>(
            future: _futurePosts,
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.waiting) {
                return const Center(child: CircularProgressIndicator());
              }
              if (snapshot.hasError) {
                return CustomErrorWidget(
                  message: snapshot.error.toString(),
                  onRetry: () => setState(() {
                    if (_filterUserId != null) {
                      _futurePosts = context.read<PostService>().getPostsByUser(_filterUserId!);
                    } else {
                      _futurePosts = context.read<PostService>().getPosts();
                    }
                  }),
                );
              }

              final posts = snapshot.data!;
              return ListView.builder(
                  itemBuilder: (context, index) {
                    final post = posts[index];
                    return _buildPostItem(context, post);
                  },
                  itemCount: posts.length);
            },
          ),
          // 评论列表
          FutureBuilder<List<Comment>>(
              future: _futureComments,
              builder: (context, snapshot) {
                if (snapshot.connectionState == ConnectionState.waiting) {
                  return const Center(child: CircularProgressIndicator());
                }
                if (snapshot.hasError) {
                  return CustomErrorWidget(
                    message: snapshot.error.toString(),
                    onRetry: () => setState(() {
                      _futureComments = context.read<PostService>().getAllComments();
                    }),
                  );
                }
                final comments = snapshot.data!;
                return ListView.builder(itemBuilder: (context,index){
                  final comment  = comments[index];
                  return _buildCommentItem(comment);
                },itemCount: comments.length,);
              }),
        ],
      ),
    );
  }
}

Widget _buildPostItem(BuildContext context, Post post) {
  return Card(
    margin: const EdgeInsets.symmetric(horizontal: 12,vertical: 6),
    child: ListTile(
      title: Text(
        post.title,
        style: const TextStyle(fontWeight: FontWeight.bold),
      ),
      subtitle: Text(
        post.body,
      ),
      trailing: const Icon(Icons.arrow_forward),
      onTap: ()=>_showPostDetails(context,post),
    ),
  );

}

void _showPostDetails(BuildContext context, Post post) async{
  final currentPost =  await context.read<PostService>().getPost(post.id);
  final comments = await context.read<PostService>().getCommentsForPost(currentPost.id);
  showModalBottomSheet(context: context,isScrollControlled: true,
      builder: (context)=>DraggableScrollableSheet(
        expand: false,
        initialChildSize: 0.7,
        maxChildSize: 0.9,
        builder: (context,scrollController){
          return Column(
            children: [
              AppBar(
                title: Text('帖子详情'),
                centerTitle: true,
                automaticallyImplyLeading: false,
                actions: [
                  IconButton(onPressed: ()=>Navigator.pop(context), icon:const Icon( Icons.close)),
                ],
              ),
              Expanded(child: SingleChildScrollView(
                controller: scrollController,
                child: Padding(
                  padding: const EdgeInsets.all(16),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(post.title,style: Theme.of(context).textTheme.headlineMedium),
                      const SizedBox(height: 16),
                      Text(post.body),
                      const SizedBox(height: 24,),
                      const Divider(),
                      Text('评论(${comments.length})',style: Theme.of(context).textTheme.labelMedium,),
                      const SizedBox(height: 12),
                      ...comments.map((comment)=>_buildCommentItem(comment)),
                    ],
                  ),
                ),
              ),),
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                child: ElevatedButton.icon(
                  icon: const Icon(Icons.comment),
                  label: const Text('查看所有评论'),
                  onPressed: () {
                    Navigator.pop(context); // 关闭详情面板
                    _navigateToComments(context, post);
                  },
                ),
              ),
            ],

          );
        },
      ));
}

void _navigateToComments(BuildContext context, Post post) {
  Navigator.push(
    context,
    MaterialPageRoute(
      builder: (context) => CommentsScreen(
        postId: post.id,
        postTitle: post.title,
      ),
    ),
  );
}

Widget _buildCommentItem( Comment item) {
  return Card(
    margin: const EdgeInsets.symmetric(horizontal: 12,vertical: 6),
    child: Padding(
      padding: const EdgeInsets.all(12),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(item.name,style:  const TextStyle(fontWeight: FontWeight.w600)),
          const SizedBox(height: 4),
          Text(item.body),
          const SizedBox(height: 8),
          Row(
            children: [
              const Icon(Icons.email,size: 16,),
              const SizedBox(width: 4),
              Text(
                item.email,
                style: const TextStyle(fontSize: 12,color: Colors.grey),
              )
            ],
          )
        ],
      ),
    ),
  );

}
